package com.sixth.volunteerservicesystem.Controller.theoryback;
import com.sixth.volunteerservicesystem.Service.LearnTheoryservice;
import com.sixth.volunteerservicesystem.Service.Videoservice;
import com.sixth.volunteerservicesystem.domain.Theory;
import com.sixth.volunteerservicesystem.domain.Video;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@Controller
public class addtheorycontroller {
    @Autowired
    Videoservice videoservice;
    @Autowired
    LearnTheoryservice learnTheoryservice;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @RequestMapping("/addtheory")
    public String addtheory()
    {
        return "learntheory/addtheory";
    }
    @RequestMapping("/addvideo")
    public String vodeo()
    {
        return "learntheory/addvideo";
    }
    @PostMapping("/uploadvideo")
    public String uploadvideo(Video video, HttpServletRequest request) throws IOException {
        FileOutputStream fos;
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        MultipartFile file = multipartHttpServletRequest.getFile("file");
        InputStream is = file.getInputStream();
        String path= ResourceUtils.getURL("src/main/resources").getPath()+"/static/upload/";
        fos = new FileOutputStream(new File(path+file.getOriginalFilename()));
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
            fos.write(buffer, 0, len);
        }
        String s="/upload/"+file.getOriginalFilename();
        video.setImg(s);
        videoservice.upload(video);

        return  "redirect:/theoryback";
    }
    @PostMapping("/addtheory")
    public String addtheory(Theory theory){
        learnTheoryservice.save(theory);
        return "redirect:/theoryback";
    }
}
